import ITool from '../ITool';

/**
 * 图层控制工具箱
 * @implements {ITool}
 */
class LayerControlTool extends ITool {
  constructor(_top, _impl) {
    super(_top, _impl);
    this.name = 'LayerControlTool';
    this.desc = '图层控制工具箱';
    this.layerStatus = {};
  }

  onAdd() {
    super.onAdd();
  }

  onRemove() {
    super.onRemove();
  }

  /**
   * 设置图层过滤条件
   * @param {Object} options 过滤条件参数
   * @param {Array} selected 默认选中
   */
  setLayerOption(options, selected) {
    this.LayerAndLayerIdPrefixesMap = options;
    Object.keys(options).forEach((key) => {
      // 默认全选
      this.layerStatus[key] = 'visible';
    });
    // 选中默认项
    if (selected) {
      this.show(selected);
    }
  }

  /**
   * 变换图层
   * @param {Array} layers 图层
   */
  show(layers) {
    Object.keys(this.layerStatus).forEach((key) => {
      if (layers.indexOf(key) > -1) {
        if (this.layerStatus[key] !== 'visible') {
          this.layerStatus[key] = 'visible';
          this.changeLayerStatus(key, 'visible');
        }
      } else if (this.layerStatus[key] !== 'none') {
        this.layerStatus[key] = 'none';
        this.changeLayerStatus(key, 'none');
      }
    });
  }

  /**
   * 修改图层显示状态
   * @param {String} type 修改类型
   * @param {String} visibility 是否显示
   * @ignore
   */
  changeLayerStatus(type, visibility) {
    let layerIdPrefixes = this.LayerAndLayerIdPrefixesMap[type];
    let layers = this.getControlLayersByPrefixes(layerIdPrefixes);
    let map = this.getMap();
    layers.forEach((layerId) => {
      if(map.getLayer(layerId)) {
        map.setLayoutProperty(layerId, 'visibility', visibility);
      }
    });
  }

  /**
   * 根据前缀获取控制图层
   * @param {Array} layerIdPrefixes 图层前缀集合
   * @ignore
   */
  getControlLayersByPrefixes(layerIdPrefixes) {
    let layers = [];
    let totalLayers = Object.keys(this.getMap().style._layers);
    totalLayers.forEach((layerId) => {
      if (this.hasSamePrefix(layerIdPrefixes, layerId)) {
        layers.push(layerId);
      }
    });
    return layers;
  }

  /**
   * 图层Id是否含有指定前缀
   * @param {Array} layerIdPrefixes 图层前缀集合
   * @param {String} layerId 图层Id
   * @ignore
   */
  hasSamePrefix(layerIdPrefixes, layerId) {
    return layerIdPrefixes.some((item) => {
      return layerId.indexOf(item) === 0;
    });
  }
}

export default LayerControlTool;
